using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Feeds.Interop;
using System.IO;

namespace RSStoZPL
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!timer1.Enabled)
            {
                FeedsManager feedManager = new FeedsManagerClass();
                IFeedFolder root = feedManager.RootFolder as IFeedFolder;
                ProcessFolder(root);
                timer1.Enabled = true;
                button1.Text = "Running...";
            }
            else
            {
                timer1.Enabled = false;
                button1.Text = "Go";
            }
        }

        private void ProcessFolder(IFeedFolder folder)
        {
            foreach (IFeedFolder subfolder in folder.Subfolders as IFeedsEnum)
            {
                ProcessFolder(subfolder);
            }
            foreach (IFeed feed in folder.Feeds as IFeedsEnum)
            {
                ProcessFeed(feed);
            }
        }

        private void ProcessFeed(IFeed feed)
        {
            if (feed.DownloadEnclosuresAutomatically)
            {
                ZunePlaylist feedPlaylist = new ZunePlaylist();
                feedPlaylist.Title = feed.Title;
                string feedDir = Path.Combine(RSStoZPL.Properties.Settings.Default.FeedFileLocation, ZunePlaylist.CleanupFilename(feed.Title));
                if (!Directory.Exists(feedDir))
                {
                    Directory.CreateDirectory(feedDir);
                }
                foreach (IFeedItem feedItem in feed.Items as IFeedsEnum)
                {
                    ProcessFeedItem(feedPlaylist, feedItem, feedDir);
                }
                if(RSStoZPL.Properties.Settings.Default.CleanUpFeeds)
                {
                    List<string> filesOnDisk = new List<string>(Directory.GetFiles(feedDir));
                    foreach (string fileOnDisk in filesOnDisk)
                    {
                        if(feedPlaylist.Items.Find(
                            delegate(ZunePlaylist.ZunePlaylistItem item)
                            {
                                if (item.MediaFile == fileOnDisk)
                                    return true;
                                return false;
                            }) == null)
                        {
                            File.Delete(fileOnDisk);
                        }
                    }
                }
                if (feedPlaylist.Items.Count > 0)
                {
                    string goodFileName = ZunePlaylist.CleanupFilename(feedPlaylist.Title);
                    feedPlaylist.Save(Path.ChangeExtension(Path.Combine(RSStoZPL.Properties.Settings.Default.PlayListLocation, goodFileName), ".zpl"));
                    backgroundWorker1.ReportProgress(50, string.Format("Created {0} with {1} items", feedPlaylist.Title, feedPlaylist.Items.Count));
                }
            }
        }

        private void ProcessFeedItem(ZunePlaylist feedPlaylist, IFeedItem feedItem, string feedDir)
        {
            if (feedItem.Enclosure != null)
            {
                IFeedEnclosure enclosure = feedItem.Enclosure as IFeedEnclosure;
                if (enclosure.DownloadStatus == FEEDS_DOWNLOAD_STATUS.FDS_DOWNLOADED)
                {
                    string newLocalLocation = Path.Combine(feedDir, Path.GetFileName(enclosure.LocalPath));
                    if(!File.Exists(newLocalLocation))
                        File.Move(enclosure.LocalPath, newLocalLocation);
                    feedPlaylist.Items.Add(new ZunePlaylist.ZunePlaylistItem(newLocalLocation));
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            button1.Text = "Running...";
            notifyIcon1.ShowBalloonTip(5000);
            backgroundWorker1.RunWorkerAsync();
            this.Hide();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            FeedsManager feedManager = new FeedsManagerClass();
            IFeedFolder root = feedManager.RootFolder as IFeedFolder;
            ProcessFolder(root);
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            notifyIcon1.BalloonTipText = e.UserState as string;
            notifyIcon1.ShowBalloonTip(5000);
        }

        private void runNowMenuItem_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        private void closeMenuItem_Click(object sender, EventArgs e)
        {
            notifyIcon1.Visible = false;
            Application.Exit();
        }

        private void setPlaylistLocationMenuItem_Click(object sender, EventArgs e)
        {
            string newPath = GetFolderPath(RSStoZPL.Properties.Settings.Default.PlayListLocation);
            if (!string.IsNullOrEmpty(newPath))
            {
                RSStoZPL.Properties.Settings.Default.PlayListLocation = newPath;
                RSStoZPL.Properties.Settings.Default.Save();
            }
        }

        private void setEnclosureLocationMenuItem_Click(object sender, EventArgs e)
        {

            string newPath = GetFolderPath(RSStoZPL.Properties.Settings.Default.FeedFileLocation);
            if (!string.IsNullOrEmpty(newPath))
            {
                RSStoZPL.Properties.Settings.Default.FeedFileLocation = newPath;
                RSStoZPL.Properties.Settings.Default.Save();
            }
        }

        private string GetFolderPath(string defaultPath)
        {
            FolderBrowserDialog diag = new FolderBrowserDialog();
            diag.SelectedPath = defaultPath;
            if (diag.ShowDialog(this) == DialogResult.OK)
                return diag.SelectedPath;
            else
                return null;
        }
    }
}